<?php

namespace App\Http\Controllers\Api;

use App\Models\User;
use App\Models\UserRole;
use App\Transformers\UserTransformer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class AccountController extends Controller
{
    public function index(Request $request)
    {
        $query = (new User())->newQuery();
        if ($name = $request->input('name')) {
            $query->where('name', 'like', '%'.$name.'%');
        }
        $query->where('id', '<>', 1);
        $query->orderBy('created_at', 'desc');
        $users = $query->paginate(20);

        return $this->response->paginator($users, new UserTransformer());
    }

    public function show(User $user)
    {
        return $this->response->item($user, new UserTransformer());
    }

    public function store(Request $request)
    {
        $check = User::where('name', $request->input('name'))->first();
        if ($check) {
            return response()->json([
                'status' => 400,
                'message' => '账号已存在'
            ]);
        }
        $user = User::create([
            'name' => $request->input('name'),
            'email' => $request->input('email'),
            'password' => Hash::make($request->input('password'))
        ]);

        UserRole::create([
            'user_id' => $user->id,
            'role_id' => 4
        ]);

        return $this->response->item($user, new UserTransformer());
    }

    public function update(User $user, Request $request)
    {
        if ($request->input('password')) {
            $user->update([
                'email' => $request->input('email'),
                'password' => Hash::make($request->input('password')),
            ]);
        } else {
            $user->update([
                'email' => $request->input('email'),
            ]);
        }

        return $this->response->item($user, new UserTransformer());
    }

    public function destroy(User $user)
    {
        $user->delete();
        return $this->response->noContent();
    }
}
